import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { InputNumber } from 'antd';
import 'moment/locale/zh-cn';
import { NoQueryC, TableC } from '../../../../../../comps';
import myStyle from '../../index.less';
import colors from '../../../../../../css/colors';
import uuid from 'es6-uuid';

@connect(({ optimizationM, loading }) => ({
  optimizationM,
  loading,
}))
@Form.create()
export default class RiskC extends PureComponent {
  state = {
    dataSource: [], //表格数据
    errorMsg: '', //错误提示消息
    columns: [
      { key: 'factorCnName', title: '风险因子' },
      { key: 'exposureInit', title: '初始组合超额暴露度', align: 'right' },
      { key: 'exposureBottom', title: '组合超额暴露度下界', align: 'right' },
      { key: 'exposureTop', title: '组合超额暴露度上界' },
    ],
  };

  componentDidMount() {
    this.props.onRef(this);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.riskArgs) != JSON.stringify(this.props.riskArgs) && this.props.typeStatus != 3) {
      if (this.props.typeStatus == 2) {
        if (!this.props.riskArgs) return; //编辑回填查询的时候不再请求
      }
      if (nextProps.riskArgs) this.queryRiskTable(nextProps.riskArgs);
    }
  }
  //查询风险因子表格
  queryRiskTable = (args) => {
    this.props.dispatch({
      type: 'optimizationM/queryRisk',
      payload: {
        ...args,
      },
      callback: (data) => {
        if (data) {
          data.map((item) => {
            item.key = uuid(16);
            item.minNum = item.exposureBottom;
            item.maxNum = item.exposureTop;
          });
          this.setState({ dataSource: data || [] });
        } else {
          this.setState({ dataSource: [] });
        }
      },
    });
  };

  //校验每行数据
  checkObj = (arr, obj) => {
    for (var i = 0; i < arr.length; i++) {
      let key = arr[i];
      if (obj[key] !== 0 && !obj[key]) {
        this.setState({
          errorMsg: '请设置完整的条件!',
        });
        return key;
      }
    }
    return null;
  };

  //表格提交
  submit = () => {
    const { dataSource, columns } = this.state;
    var msg = '';
    var columnKeys = columns.map((item) => {
      return item.key;
    });
    for (var i = 0; i < dataSource.length; i++) {
      var item = dataSource[i];
      item.isRed = false;
      var index = this.checkObj(columnKeys, item); //判断是否都填写
      if (index) {
        item.isRed = true;
        this.setState({
          dataSource: [...dataSource],
        });
        return null;
      }
      if (item.minNum && item.maxNum) {
        if (item.minNum > item.maxNum || item.minNum == item.maxNum) {
          msg = '权重上界必须大于权重下界';
          this.setState({
            errorMsg: msg,
          });
          item.isRed = true;
          this.setState({
            dataSource: [...dataSource],
          });
          return null;
        }
      }
    }

    this.setState({
      errorMsg: '',
    });
    return dataSource.length ? dataSource : undefined;
  };

  //父组件点击重置按钮
  reset = () => {
    this.setState({
      dataSource: [],
      errorMsg: '', //错误提示消息
    });
  };

  //初始化表格
  initTable = () => {
    const { dataSource, errorMsg, columns } = this.state;
    const { loading, typeStatus } = this.props;
    columns.map((item) => {
      if (typeStatus != 3 && (item.key == 'exposureBottom' || item.key == 'exposureTop')) {
        item.render = (text, record) => {
          //设置展示的form表单
          let min = undefined;
          let max = undefined;
          min = Number(record.minNum);
          max = Number(record.maxNum);
          return (
            <InputNumber
              value={Number(record[item.key])}
              className={errorMsg && record.isRed ? myStyle.hasError : ''}
              min={min}
              max={max}
              step={0.1}
              precision={4}
              placeholder={item.key == 'exposureBottom' ? min : max}
              style={{ width: '100%' }}
              onChange={(value) => {
                record[item.key] = value;
                dataSource.map((row) => {
                  if (row.key == record.key) {
                    row = { ...record };
                  }
                });
                this.setState({
                  //渲染表格,使修改生效
                  dataSource: [...dataSource],
                });
              }}
            />
          );
        };
      }
    });
    return (
      <TableC columns={columns} dataSource={dataSource} rowKey='key' scroll={{ x: '100%', y: 270 }} hidePage={true} loading={loading.effects['optimizationM/queryRisk'] == true} />
    );
  };

  render() {
    const { errorMsg } = this.state;

    return (
      <div className={myStyle.tableForm}>
        {this.props.riskArgs || this.props.typeStatus != '1' ? (
          <>
            {this.initTable()}
            <div className='addRow'>
              <span style={{ display: errorMsg ? 'inherit' : 'none', color: colors.debtAndProfit.text[0], top: '-6px', left: '-2px', fontSize: '12px' }}>{errorMsg}</span>
            </div>
          </>
        ) : (
          <NoQueryC title='权重调整后，点击“刷新”得到最新的风格因子暴露度值' />
        )}
      </div>
    );
  }
}
